package com.uxwine.view.t;

import com.uxwine.alarm.R;
import com.uxwine.util.Log;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class DigitalView extends LinearLayout {
	
	private ImageView mMarker;
	private LinearLayout mCtnMain;
	private Bitmap[] mSelectBitmaps, mNormalBitmaps, mDisableBitmaps;
	private ImageView[] mViews;
	private int mnMedian;
	private int mnDigital;
	private boolean mbShowMarker;
	private static final String TAG = DigitalView.class.getName();

	public DigitalView(Context context, AttributeSet attrs) {
		super(context, attrs);
		TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.DigitalView);
		mnMedian = arr.getInt(R.styleable.DigitalView_median, 2);
		arr.recycle();
		initView(context);
	}
	
	public synchronized void setBitmaps(Bitmap[] n, Bitmap[] s, Bitmap[] d)
	{
		mNormalBitmaps = n;
		mSelectBitmaps = s;
		mDisableBitmaps = d;
	}
	
	public void setValue(int value)
	{
		mnDigital = value;
	}
	
	public int getValue()
	{
		return mnDigital;
	}
	
	public void setShowMarker(boolean isShowMarker)
	{
		mbShowMarker = isShowMarker;
	}
	
	public synchronized void updateView()
	{
		mMarker.setVisibility(mbShowMarker ? View.VISIBLE : View.INVISIBLE);
		
		Bitmap[] bms = getBitmapsByCurrentState();
		if(bms == null)
			return;
		Log.i(TAG, mnDigital + "");
		int d = mnDigital;
		for(int i = 0; i < mnMedian; i++)
		{
			int n = d % 10;
			d = d / 10;
			mViews[i].setImageBitmap(bms[n]);
		}
	}	
	
	private Bitmap[] getBitmapsByCurrentState()
	{		
		if(isEnabled())
		{
			return isSelected() ? mSelectBitmaps : mNormalBitmaps;
		}
		else
		{
			return mDisableBitmaps;
		}
	}
	
	private void initView(Context context)
	{
		LayoutInflater inflater = LayoutInflater.from(context);
		inflater.inflate(R.layout.view_time_span_digtal, this);
		mMarker = (ImageView)findViewById(R.id.digital_iv_marker);
		mCtnMain = (LinearLayout)findViewById(R.id.digital_ctn_main);
		mViews = new ImageView[mnMedian];
		for(int i = mnMedian - 1; i >= 0; i--)
		{
			mViews[i] = initImageView(context);
			mCtnMain.addView(mViews[i]);
		}
	}
	
	private ImageView initImageView(Context context)
	{
		ImageView v = new ImageView(context);
		final LinearLayout.LayoutParams lp = 
				new LayoutParams(0, LayoutParams.MATCH_PARENT);
		lp.weight = 1;
		v.setLayoutParams(lp);
		return v;
	}
	
//	@Override
//	protected void onLayout(boolean changed, int l, int t, int r, int b) {
//
//		int count = getChildCount();
//		int len = (r - l) / mnMedian;
//		for(int i = 0; i < count; i++)
//		{
//			View v = getChildAt(i);
//			if(null == v)
//				continue;
//			int left = l + i * len;
//			int right = left + len;
//			v.setBackgroundColor(Color.RED);
//			v.layout(left, t, right, b);
//		}		
//	}

}
